package com.hss.thread.wait;

import java.util.Random;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * https://www.cnblogs.com/zl1991/p/6930160.html
 *   2. 使用wait/notifyAll，这个方式其实跟上面是类似的，只是比较底层些吧(join实际上也是wait)。
 */
public class WaitThread_Wait {
    public static final int TEST_THREAD_COUNT = 10;
    public static void printSortedResult(Vector<Integer> list) {
        for (Integer item : list) {
            System.out.println(item == null ? "null" : item);
        }
    }
    public static void test(){
        final Object waitObject = new Object();
        final AtomicInteger count = new AtomicInteger(TEST_THREAD_COUNT);
        final Vector<Integer> list = new Vector<>();
        Thread[] threads = new Thread[TEST_THREAD_COUNT];
        Random random = new Random();

        for (int i=0;i<TEST_THREAD_COUNT;i++){
            final int num = i;
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(random.nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    list.add(num);
                    System.out.print(num + " add.\t");
                    synchronized (waitObject){
                        int cnt = count.decrementAndGet();
                        if (cnt == 0){
                            waitObject.notifyAll();
                        }
                    }
                }
            });
            threads[i].start();
        }

       synchronized (waitObject){
            while (count.get() != 0){
                try {
                    waitObject.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
       }
       printSortedResult(list);
    }

    public static void main(String[] args) {
        test();
    }
}
